var express = require("express");
var router = express.Router();
const mysql = require("../util/mysql/mysql");

//添加地址
router.post("/addSite", function (req, res, next) {
    const data = req.body;
    mysql.data(
        "INSERT INTO my_site(name,area,site,phone,other,u_id,muo) VALUES (?,?,?,?,?,?,?)",
        [
            data.name,
            data.area,
            data.site,
            data.phone,
            data.other,
            data.u_id,
            data.muo,
        ],
        function (err, rows, fields) {
            if (err) {
                console.log(err);
                return;
            }
            res.send(JSON.stringify({ code: 1 }));
        }
    );
});
//购物车信息
router.post("/shopcarData", function (req, res, next) {
    mysql.data(
        "UPDATE shop_car SET g_check=0",
        [],
        function (err, rows, fields) {
            if (err) {
                console.log(err);
                return;
            }
            mysql.data("SELECT s_id from goods a INNER JOIN shop_car b ON b.g_id=a.id where user_id=" + req.body.u_id, [], function (err, rows, fields) {
                if (err) {
                    console.log(err);
                    return;
                }
                var s_arr = [];
                for (var i = 0; i < rows.length; i++) {
                    s_arr.push(rows[i].s_id);
                }
                const new_sarr = [...new Set(s_arr)];
                var prom = [];
                for (var i = 0; i < new_sarr.length; i++) {
                    prom.push(
                        new Promise((resolve, reject) => {
                            var num = i;
                            mysql.data(
                                "select * from store where s_id=" + new_sarr[num],
                                [],
                                function (err1, rows1, fields) {
                                    if (err1) {
                                        reject(err1);
                                        return;
                                    }
                                    mysql.data(
                                        "SELECT * from goods a INNER JOIN shop_car b ON b.g_id=a.id where s_id=" +
                                        new_sarr[num],
                                        [],
                                        function (err1, rows2, fields) {
                                            if (err1) {
                                                reject(err1);
                                                return;
                                            }
                                            const newObj = { ...rows1[0], good: rows2 };
                                            resolve(newObj);
                                        }
                                    );
                                }
                            );
                        })
                    );
                }
                Promise.all(prom).then((ress) => {
                    res.send(JSON.stringify(ress));
                });
            });
        }
    );

});
//删除购物车
router.post("/delShopcar", function (req, res, next) {
    mysql.data(
        "delete from shop_car where car_id=" + req.body.car_id,
        [],
        function (err, rows, fields) {
            if (err) {
                console.log(err);
                return;
            }
            res.send(JSON.stringify({ code: 1 }));
        }
    );
});
//批量删除购物车
router.post("/delsShopcar", function (req, res, next) {
    const dalarr = req.body.delarr;
    const rescode = [];
    for (var i = 0; i < dalarr.length; i++) {
        rescode.push(
            new Promise((resolve, reject) => {
                var num = i;
                mysql.data(
                    "delete from shop_car where car_id=" + dalarr[num],
                    [],
                    function (err, rows, fields) {
                        if (err) {
                            console.log(err);
                            return;
                        }
                        resolve(1)
                    }
                );
            })
        )
    }
    Promise.all(rescode).then((ress) => {
        res.send(JSON.stringify({ code: 1 }));
    });
});
//修改购物车信息
router.post("/updateShopcar", function (req, res, next) {
    const updateArr = req.body.updateArr;
    var updatePrm = [];
    for (var i = 0; i < updateArr.length; i++) {
        var num = i;
        updatePrm.push(
            new Promise((resolve, reject) => {
                mysql.data(
                    "UPDATE shop_car SET g_num=?,g_check=1 WHERE car_id=? ",
                    [updateArr[num].g_num, updateArr[num].car_id],
                    function (err, rows, fields) {
                        if (err) {
                            console.log(err);
                            return;
                        }
                        resolve(1)
                    });
            })
        )
    }
    Promise.all(updatePrm).then((ress) => {
        res.send(JSON.stringify({ code: 1 }));
    })
});
//订单预处理
router.post("/shopData", function (req, res, next) {
    mysql.data("SELECT s_id from goods a INNER JOIN shop_car b ON b.g_id=a.id where user_id=? and g_check=1", [req.body.u_id], function (err, rows, fields) {
        if (err) {
            console.log(err);
            return;
        }
        var s_arr = [];
        for (var i = 0; i < rows.length; i++) {
            s_arr.push(rows[i].s_id);
        }
        const new_sarr = [...new Set(s_arr)];
        var prom = [];
        for (var i = 0; i < new_sarr.length; i++) {
            prom.push(
                new Promise((resolve, reject) => {
                    var num = i;
                    mysql.data(
                        "select * from store where s_id=" + new_sarr[num],
                        [],
                        function (err1, rows1, fields) {
                            if (err1) {
                                reject(err1);
                                return;
                            }
                            mysql.data(
                                "SELECT * from goods a INNER JOIN shop_car b ON b.g_id=a.id where g_check=1 and s_id=" +
                                new_sarr[num],
                                [],
                                function (err1, rows2, fields) {
                                    if (err1) {
                                        reject(err1);
                                        return;
                                    }
                                    const newObj = { ...rows1[0], good: rows2 };
                                    resolve(newObj);
                                }
                            );
                        }
                    );
                })
            );
        }
        Promise.all(prom).then((ress) => {
            res.send(JSON.stringify(ress));
        });
    });
});
// 创建订单
router.post("/addBill", function (req, res, next) {
    const data = req.body.addBill;
    var bill = []
    //生成订单
    for (var i = 0; i < data.length; i++) {
        var num1 = i;
        bill.push(
            new Promise((resolve1, reject1) => {
                var bill_num = Math.floor(Math.random() * (999999999 - 100000000) + 100000000);
                mysql.data(
                    "INSERT INTO my_bill(shop_id,b_num,crea_time,b_price,b_type,b_site) VALUES (?,?,?,?,?,?)",
                    [
                        data[num1].shop_id,
                        bill_num,
                        '2021-12-2 14:17:00',
                        data[num1].zj,
                        2,
                        '已付款代发货',
                    ],
                    function (err, rows1, fields) {
                        if (err) {
                            console.log(err);
                            return;
                        }
                        mysql.data(
                            "select b_id from my_bill where b_num=" + bill_num,
                            [],
                            function (err, rows2, fields) {
                                if (err) {
                                    console.log(err);
                                    return;
                                }
                                var b_id = rows2[0].b_id;
                                resolve1(b_id)
                            }
                        );
                    }
                );
            })
        )
    }
    Promise.all(bill).then((res1) => {
        var billgood = [];
        //生成订单中商品
        for (var i = 0; i < res1.length; i++) {
            for (var j = 0; j < data[i].good.length; j++) {
                var num1 = i;
                var num2 = j;
                billgood.push(
                    new Promise((resolve, reject2) => {
                        mysql.data(
                            "INSERT INTO bill_goods(good_id,g_num,bill_id) VALUES (?,?,?)",
                            [
                                data[num1].good[num2].g_id,
                                data[num1].good[num2].g_num,
                                res1[i],
                            ],
                            function (err, rows1, fields) {
                                if (err) {
                                    console.log(err);
                                    return;
                                }
                                resolve(2)
                            }
                        );
                    })
                )
            }
        }
        Promise.all(billgood).then(() => {
            mysql.data(
                "delete from shop_car where g_check=1",
                [],
                function (err, rows1, fields) {
                    if (err) {
                        console.log(err);
                        return;
                    }
                    res.send(JSON.stringify({ code: 1 }));
                }
            );
        })
    })
});
//查询订单
router.post("/selectBill", function (req, res, next) {
    mysql.data(
        "select * from my_bill where b_id=" + req.body.b_id,
        [],
        function (err, rows, fields) {
            if (err) {
                console.log(err);
                return;
            }
            res.send(JSON.stringify(rows[0]));
        }
    );
});
//积分订单预处理
router.post("/JfBill", function (req, res, next) {
    mysql.data(
        "select title,gui_ge,jf from goods where id=" + req.body.id,
        [],
        function (err, rows, fields) {
            if (err) {
                console.log(err);
                return;
            }
            res.send(JSON.stringify(rows[0]));
        }
    );
});
//立刻购买订单预处理
router.post("/shopNow", function (req, res, next) {
    mysql.data(
        "SELECT title,name,new_price  from goods a INNER JOIN store b ON a.s_id=b.s_id where id=" + req.body.id,
        [],
        function (err, rows, fields) {
            if (err) {
                console.log(err);
                return;
            }
            res.send(JSON.stringify(rows[0]));
        }
    );
});
// 创建积分订单
router.post("/addjfBill", function (req, res, next) {
    const data = req.body.addjfBill;
    var bill_num = Math.floor(Math.random() * (999999999 - 100000000) + 100000000);
    mysql.data(
        "INSERT INTO jf_bill(good_id,g_num,jfb_num,jfb_time,jfb_type,jfb_state) VALUES (?,?,?,?,?,?)",
        [data.g_id,
        data.g_num,
            bill_num,
            '2021-12-2 14:17:00',
            2,
            '已付款代发货',
        ],
        function (err, rows1, fields) {
            if (err) {
                console.log(err);
                return;
            }
            res.send(JSON.stringify({ code: 1 }));
        }
    );
})
//订单付款
router.post("/pay", function (req, res, next) {
    mysql.data(
        "SELECT wallet from userdata where u_id=1",
        [req.body.pay],
        function (err, rows, fields) {
            if (err) {
                console.log(err);
                return;
            } else if (rows[0].wallet >= req.body.pay) {
                mysql.data(
                    "UPDATE userdata SET wallet=wallet-? where u_id=1",
                    [req.body.pay],
                    function (err, rows, fields) {
                        if (err) {
                            console.log(err);
                            return;
                        }
                        mysql.data(
                            "select wallet from userdata where u_id=1",
                            [],
                            function (err2, rows2, fields) {
                                if (err2) {
                                    console.log(err2);
                                    return;
                                }
                                mysql.data(
                                    "INSERT INTO my_record(r_type,r_num,r_time,r_yu) VALUES (?,?,?,?)",
                                    ['消费', req.body.wallet, '2021-12-13', rows2[0].wallet],
                                    function (err3, rows, fields) {
                                        if (err3) {
                                            console.log(err3);
                                            return;
                                        }
                                        res.send(JSON.stringify({ code: 1 }));
                                    }
                                );
                            }
                        );
                    }
                );
            } else {
                res.send(JSON.stringify({ code: 2 }));
            }

        }
    );
});

module.exports = router;
